package com.fbt.transfer.app.driver.activity;

import android.view.View;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import cn.hutool.core.text.StrPool;
import com.fbt.transfer.app.driver.adapter.BalanceAdapter;
import com.fbt.transfer.app.driver.databinding.ActivityMyBalanceBinding;
import com.fbt.transfer.app.driver.http.AbstractCallback;
import com.fbt.transfer.app.driver.model.PageInfo;
import com.fbt.transfer.app.driver.model.Result;
import com.fbt.transfer.app.driver.model.me.AccountDetailVo;
import com.fbt.transfer.app.driver.model.me.AccountFlowUnit;
import com.fbt.transfer.app.driver.model.me.BalanceInfoVo;
import com.fbt.transfer.app.driver.util.LogUtils;
import com.fbt.transfer.app.driver.util.ZMToast;
import com.fbt.transfer.app.driver.widget.MonthYearPickerDialog;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

/**
 * 我的余额页面
 *
 * @author tuocoo
 * @date 2024-11-15
 * @since 1.0.0
 */
public class MyBalanceActivity extends BaseActivity {

  private static final String TAG = "MyBalanceActivity";
  private static final int PAGE_SIZE = 10;

  private BalanceAdapter adapter = null;
  private List<AccountFlowUnit> flowList = new ArrayList<>();
  private int currentPage = 1;
  private boolean hasMoreData = true;
  private boolean isLoading = false;
  private int totalPages = 0;
  /**
   * 当前选择的年月，格式：yyyy-MM
   */
  private static String currentMonth = null;
  private ActivityMyBalanceBinding activityMyBalanceBinding = null;

  static {
    LocalDate today = LocalDate.now();
    int month = today.getMonthValue();
    currentMonth = today.getYear() + StrPool.DASHED + (month < 10 ? "0" + month : month);
  }

  @Override
  public void initView () {
    activityMyBalanceBinding = ActivityMyBalanceBinding.inflate(getLayoutInflater());
    setContentView(activityMyBalanceBinding.getRoot());
    setTitle("我的余额");
    apiInterface.lastFlowDate().enqueue(new AbstractCallback<String>(MyBalanceActivity.this, true) {

      @Override
      protected void onSuccess (String lastDate) {
        currentMonth = activityMyBalanceBinding.tvDatePicker.getText().toString();
        activityMyBalanceBinding.tvDatePicker.setText(currentMonth);
      }
    });
    activityMyBalanceBinding.tvDatePicker.setText(currentMonth);
    activityMyBalanceBinding.tvDatePicker.setOnClickListener(v -> showMonthYearPicker());
    // 设置RecyclerView
    LinearLayoutManager layoutManager = new LinearLayoutManager(this);
    activityMyBalanceBinding.recyclerView.setLayoutManager(layoutManager);
    adapter = new BalanceAdapter(this);
    activityMyBalanceBinding.recyclerView.setAdapter(adapter);
  }

  @Override
  public void initListener () {
    // 下拉刷新
    activityMyBalanceBinding.swipeRefreshLayout.setOnRefreshListener(() -> {
      currentPage = 1;
      hasMoreData = true;
      loadData();
    });

    // 初始加载数据
    loadData();

    // 滚动监听：仅支持向下加载更多
    activityMyBalanceBinding.recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
      private boolean hasShownNoMoreDataToast = false;
      
      @Override
      public void onScrolled (@NonNull RecyclerView recyclerView, int dx, int dy) {
        super.onScrolled(recyclerView, dx, dy);

        LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
        int visibleItemCount = layoutManager.getChildCount();
        int totalItemCount = layoutManager.getItemCount();
        int lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition();

        if (!isLoading && dy > 0) {
          if (hasMoreData) {
            // 当滚动到倒数第3个item时开始加载，提前加载避免卡顿
            if (lastVisibleItemPosition >= totalItemCount - 3 && totalItemCount >= PAGE_SIZE) {
              loadMoreData();
            }
          } else {
            // 已经没有更多数据，用户继续向下滑动时提示
            // 当滑动到倒数第2个item时就开始提示，提升用户体验
            if (lastVisibleItemPosition >= totalItemCount - 2 && totalItemCount > 0 && !hasShownNoMoreDataToast) {
              ZMToast.info(MyBalanceActivity.this, "没有更多数据了");
              hasShownNoMoreDataToast = true;
              // 延迟重置标志，避免频繁提示
              recyclerView.postDelayed(() -> hasShownNoMoreDataToast = false, 2000);
            }
          }
        }
      }
    });
  }

  /**
   * 加载余额和流水数据
   */
  private void loadData () {
    // 加载余额信息
    loadBalanceInfo();
    // 加载流水记录
    loadFlowData(true);
  }

  /**
   * 加载余额信息
   */
  private void loadBalanceInfo () {
    apiInterface.queryBalance()
        .enqueue(new AbstractCallback<BalanceInfoVo>(MyBalanceActivity.this, true) {
          @Override
          public void onSuccess (BalanceInfoVo balanceInfo) {
            updateBalanceInfo(balanceInfo);
          }
        });
  }

  /**
   * 更新余额信息UI
   */
  private void updateBalanceInfo (BalanceInfoVo balanceInfo) {
    // 更新UI
    activityMyBalanceBinding.tvTotalBalance.setText(balanceInfo.getTotal());
    activityMyBalanceBinding.tvWithdrawableBalance.setText(balanceInfo.getWithdrawalAmount());
    activityMyBalanceBinding.tvSettlingBalance.setText(balanceInfo.getSettlementingAmount());
    activityMyBalanceBinding.tvFrozenBalance.setText(balanceInfo.getFreeze());
  }

  /**
   * 加载流水记录
   *
   * @param isRefresh 是否是刷新操作
   */
  private void loadFlowData (boolean isRefresh) {
    if (isRefresh) {
      currentPage = 1;
    }
    isLoading = true;
    apiInterface.accountDetailList(currentPage, PAGE_SIZE, currentMonth)
        .enqueue(new AbstractCallback<AccountDetailVo>(MyBalanceActivity.this, true) {
          @Override
          protected void onSuccess (AccountDetailVo detailVo) {
            activityMyBalanceBinding.swipeRefreshLayout.setRefreshing(false);
            isLoading = false;
            // 更新当月收支
            updateMonthlyStats(detailVo);
            // 更新分页信息
            PageInfo<AccountFlowUnit> pageInfo = detailVo.getPageDataV3();
            if (pageInfo != null) {
              totalPages = (int) pageInfo.getPages();
              hasMoreData = pageInfo.hasNext();
            }
            // 更新流水列表
            updateFlowList(pageInfo, isRefresh);
          }

          @Override
          protected void onFailure (Result<AccountDetailVo> result) {
            activityMyBalanceBinding.swipeRefreshLayout.setRefreshing(false);
            isLoading = false;
            LogUtils.e(TAG, "加载流水记录失败: " + result.getMessage());
            ZMToast.err(MyBalanceActivity.this, "加载流水记录失败: " + result.getMessage());
            if (isRefresh) {
              checkEmptyView();
            }
          }


        });
  }

  /**
   * 加载更多流水记录
   */
  private void loadMoreData () {
    if (!hasMoreData || isLoading || currentPage >= totalPages) {
      return;
    }

    currentPage++;
    loadFlowData(false);
  }

  /**
   * 更新当月收支统计
   */
  private void updateMonthlyStats (AccountDetailVo detailVo) {
    activityMyBalanceBinding.tvMonthlyIncome.setText(detailVo.getCurrentMonthAmount());
    activityMyBalanceBinding.tvMonthlyExpense.setText(detailVo.getCurrentMonthPayout());
  }

  /**
   * 更新流水列表
   */
  private void updateFlowList (PageInfo<AccountFlowUnit> pageInfo, boolean isRefresh) {
    if (pageInfo == null) {
      return;
    }

    List<AccountFlowUnit> list = pageInfo.getRecords();

    if (list == null || list.isEmpty()) {
      if (isRefresh) {
        flowList.clear();
        adapter.setData(flowList);
      }
      hasMoreData = false;
      checkEmptyView();
      return;
    }

    if (isRefresh) {
      // 刷新时清空并重新加载
      flowList.clear();
      flowList.addAll(list);
    } else {
      // 加载更多时追加数据，保持原有数据顺序
      flowList.addAll(list);
    }
    
    adapter.setData(flowList);

    // 更新分页状态
    hasMoreData = pageInfo.hasNext();

    checkEmptyView();
  }

  /**
   * 检查是否显示空视图
   */
  private void checkEmptyView () {
    if (flowList.isEmpty()) {
      activityMyBalanceBinding.emptyView.setVisibility(View.VISIBLE);
      activityMyBalanceBinding.recyclerView.setVisibility(View.GONE);
    } else {
      activityMyBalanceBinding.emptyView.setVisibility(View.GONE);
      activityMyBalanceBinding.recyclerView.setVisibility(View.VISIBLE);
    }
  }

  /**
   * 格式化金额显示
   */
  private String formatAmount (BigDecimal amount) {
    if (amount == null) {
      return "0.00";
    }
    return amount.setScale(2, BigDecimal.ROUND_HALF_UP).toString();
  }

  /**
   * 显示年月选择器
   */
  private void showMonthYearPicker () {
    // 解析当前选择的年月
    String[] parts = currentMonth.split(StrPool.DASHED);
    int year = Integer.parseInt(parts[0]);
    int month = Integer.parseInt(parts[1]);

    // 创建自定义年月选择器
    LocalDate now = LocalDate.now();
    MonthYearPickerDialog dialog = new MonthYearPickerDialog(this, now.getYear(), now.getMonthValue());
    dialog.setSelectedDate(year, month);
    
    dialog.setOnDateSelectedListener((selectedYear, selectedMonth) -> {
      // 用户选择了年月
      currentMonth = String.format("%d-%02d", selectedYear, selectedMonth);
      activityMyBalanceBinding.tvDatePicker.setText(currentMonth);

      // 重新加载数据
      currentPage = 1;
      hasMoreData = true;
      loadFlowData(true);
    });
    
    dialog.show();
  }
}